//
//  XDUpdatePasswordViewController.m
//  XDEducation
//
//  Created by apple on 2017/4/10.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "XDUpdatePasswordViewController.h"
#import "XDLoginTextFieldCell.h"
#import "XDLoginHeaderView.h"
#import "XDRegisterBtnCell.h"
@interface XDUpdatePasswordViewController ()<UITextFieldDelegate>
{
    NSString *_password_1;
    NSString *_password_2;
}

/** textfield */
@property(nonatomic, strong) UITextField *passwordTextField_1;
@property(nonatomic, strong) UITextField *passwordTextField_2;
@end

static NSString *const forgetCellId = @"RegisterBtnCell";

@implementation XDUpdatePasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initTableView];
}

/**
 初始化tableView
 */
-(void)initTableView{
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.scrollEnabled = NO;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(returnKeyboard)];
    [self.tableView addGestureRecognizer:tap];
}


#pragma mark - tableview delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 3;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    XDLoginHeaderView *headerView = [[XDLoginHeaderView alloc]init];
    headerView.isForgetPassword = YES;
    //返回block
    WeakSelf(weakself)
    headerView.backBlock = ^(){
        
        [weakself dismissViewControllerAnimated:YES completion:nil];
    };
    
    return headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return (ScreenH/3 + 40 ) * ScaleHeight;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 70 * ScaleHeight;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    WeakSelf(weakself)
    switch (indexPath.row) {
        case 0:{
            
            XDLoginTextFieldCell *cell = [XDLoginTextFieldCell cellImageName:@"login_icon_password" title:@"新密码:" textFieldPalceHolder:@"请输入新密码" tableView:tableView];
            cell.hidePassword = YES;
            self.passwordTextField_1 = cell.textField;
            self.passwordTextField_1.delegate = self;
            return cell;
            
        }
            break;
            
        case 1:{
            
            XDLoginTextFieldCell *cell = [XDLoginTextFieldCell cellImageName:@"login_icon_password" title:@"新密码:" textFieldPalceHolder:@"请再次输入新密码" tableView:tableView];
            cell.hidePassword = YES;
            self.passwordTextField_2 = cell.textField;
            self.passwordTextField_2.delegate = self;
            return cell;
            
        }
            break;
        case 2:{
            
            XDRegisterBtnCell *cell = [tableView dequeueReusableCellWithIdentifier:forgetCellId];
            if (!cell) {
                [tableView registerNib:[UINib nibWithNibName:@"XDRegisterBtnCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:forgetCellId];
                cell = [tableView dequeueReusableCellWithIdentifier:forgetCellId];
            }
            cell.title = @"提交";
            cell.registerBlock = ^(){
                //验证码判断请求
                [weakself initNetWorking];
            };
            return cell;
            
        }
        default:
            return nil;
            break;
    }
    
    
}


#pragma mark - 网络请求
-(void)initNetWorking{
    
    [self.view endEditing:YES];
    
    //判断密码
    if(_password_1.length < 6 || _password_2.length < 6){
        [MBProgressHUD showError:@"密码格式错误"];
        return;
    }
    
    if (![_password_1 isEqualToString:_password_2]) {
        [MBProgressHUD showError:@"两次密码不一致"];
        return;
    }
    
    
    [MBProgressHUD showHUD];
    
    NSString *url = [NSString stringWithFormat:@"user.do?action=setPwd&pwd=%@&uid=%@",_password_1,self.uid];
    
    //1，创建会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    //2,根据会话创建task
    NSURL *urL = [NSURL URLWithString:[BaseURL(url) stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    //3,创建可变的请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urL];
    //4,请求方法
    request.HTTPMethod = @"POST";
    //5.根据会话创建一个task（发送请求）
    
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *  data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            //            NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            //
            //            NSLog(@"response:%@",dic);
            
            //通知主线程刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                //主线程刷新界面
                [MBProgressHUD hideHUD];
                
                [MBProgressHUD showSuccess:@"修改成功"];
                [self dismissViewControllerAnimated:YES completion:nil];
                
                [[NSNotificationCenter defaultCenter]postNotificationName:@"dismisViewController" object:nil];
                
            });   //195766
        }else{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //主线程刷新界面
                NSLog(@"%@",error);
                
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:@"网络请求失败"];
            });
            
            
        }
        
    }];
    
    [dataTask resume];
    
    
}


/**
 return 键盘
 */
-(void)returnKeyboard{
    
    [self.view endEditing:YES];
}

#pragma - mark  TextField 代理方法

//弹回键盘
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    //设置动画的名字
    [UIView beginAnimations:@"Animation" context:nil];
    //设置动画的间隔时间
    [UIView setAnimationDuration:0.20];
    //??使用当前正在运行的状态开始下一段动画
    [UIView setAnimationBeginsFromCurrentState: YES];
    //设置视图移动的位移
    self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y - 100, self.view.frame.size.width, self.view.frame.size.height);
    //设置动画结束
    [UIView commitAnimations];
}

//在UITextField 编辑完成调用方法
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    
    //赋值
    if(textField == self.passwordTextField_1){
        
        _password_1 = textField.text;
        
    }else if(textField == self.passwordTextField_2){
        
        _password_2 = textField.text;
        
    }
    
    
    //设置动画的名字
    [UIView beginAnimations:@"Animation" context:nil];
    //设置动画的间隔时间
    [UIView setAnimationDuration:0.20];
    //??使用当前正在运行的状态开始下一段动画
    [UIView setAnimationBeginsFromCurrentState: YES];
    //设置视图移动的位移
    self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y + 100, self.view.frame.size.width, self.view.frame.size.height);
    //设置动画结束
    [UIView commitAnimations];
}



@end
